﻿using NLog;
using SqlSugar;
using System;
using System.Linq;

namespace Link_eLab.Redis
{
    public class DbInstance
    {
        /// <summary>
        /// Redis链接字符串
        /// </summary>
        public static string Redis_ConnectionString { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private static Logger Logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 获取Sugar客户端实例对象
        /// </summary>
        /// <returns>SqlSugarClient</returns>
        public static SqlSugarClient GetInstance()
        {
            ConfigureExternalServices _configureExternalServices = new ConfigureExternalServices();

            // 检测是否有redis连接字符串，没有不启用二级缓存
            RedisCache.UseCache = true;
            //_configureExternalServices.DataInfoCacheService = new RedisCache(Redis_ConnectionString);
            _configureExternalServices.DataInfoCacheService = new RedisCache("127.0.0.1", 6379, "", -1, 0);

            SqlSugarClient db;

            db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = string.Empty,
                DbType = DbType.MySql,
                ConfigureExternalServices = _configureExternalServices,
            });
            db.Ado.IsEnableLogEvent = true;

            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Logger.Debug(sql);

                Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };
            return db;
        }
    }
}